package com.xzkydz.utils;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

public class Utils {
    public static String buildSign(String auCode, Map<String, String> params)
            throws UnsupportedEncodingException {

        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder sbr = new StringBuilder();
        sbr.append(auCode);
        for (String key : keys) {
            String value = params.get(key);
            if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                sbr.append(key).append(value);
                // 注意这里：将所有参数值转换为UTF-8编码，然后拼装，并作URL ENCODING
            }
        }
        return MD5Upper32(sbr.toString());
    }

    public static String MD5Upper32(String origin) throws UnsupportedEncodingException {
        String charsetName = "UTF-8";
        String key = "0123456789ABCDEF";
        String resultString = null;
        String[] hexDigits = new String[key.length()];
        for (int i = 0; i < key.length(); i++) {
            hexDigits[i] = String.valueOf(key.charAt(i));
        }
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)), hexDigits);
        } catch (Exception ex) {

        }
        return resultString;
    }

    /**
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b, String[] hexDigits) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i], hexDigits));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b, String[] hexDigits) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}